<template>
  <div class="login-page">
    <div class="bg"></div>
    <el-row class="form-container">
      <el-col :span="8" :offset="8" class="form">
        <el-form ref="ruleFormRef" :model="registerData" size="large" autocomplete="off" :rules="rules">
          <el-form-item>
            <h1>zjkoye的Crm管理系统登录</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-row>
              <el-col :span="14">
                <el-input placeholder="请输入验证码" v-model="registerData.captcha"></el-input>
              </el-col>
              <el-col :span="10">
                <canvas id="captchaCanvas" width="100" height="40" @click="refreshCaptcha"></canvas>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-link type="primary" :underline="false" @click="goToRegister">注册新账号</el-link>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { usermainLoginService } from '@/api/user'
import { useTokenStore } from '@/stores/token'
import { useRouter } from 'vue-router'

const registerData = ref({
  username: '',
  password: '',
  captcha: ''
})

const ruleFormRef = ref(null)

const validateCaptcha = (rule, value, callback) => {
  callback();                                             //为了方便 开发时候不验证
  if (value.toLowerCase() !== correctCaptcha.value.toLowerCase()) {
    callback(new Error('验证码不正确'));
  } else {
    callback();
  }
}

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator: validateCaptcha, trigger: 'blur' }
  ]
})

const router = useRouter()
const tokenStore = useTokenStore()

const login = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let result = await usermainLoginService(registerData.value)
      ElMessage.success(result.msg ? result.msg : '登录成功')
      tokenStore.setToken(result.data)
      router.push('/')
    } else {
      console.log("校验失败")
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}

const generateCaptcha = (length = 6) => {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let captcha = '';
  for (let i = 0; i < length; i++) {
    captcha += chars[Math.floor(Math.random() * chars.length)];
  }
  return captcha;
}

const drawCaptcha = (captcha) => {
  const canvas = document.getElementById('captchaCanvas');
  const ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.font = '30px Arial';
  ctx.fillText(captcha, 10, 30);
}

const correctCaptcha = ref('');

const refreshCaptcha = () => {
  correctCaptcha.value = generateCaptcha();
  drawCaptcha(correctCaptcha.value);
}

onMounted(() => {
  refreshCaptcha();
});
</script>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/login_bg.jpg') no-repeat center / cover;
  overflow: hidden;
}

.form-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form {
  width: 400px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  user-select: none;

  h1 {
    text-align: center;
    margin-bottom: 20px;
  }

  .button {
    width: 100%;
  }
}
</style>
